import os
import jinja2
import subprocess

# 读取模板文件
template_loader = jinja2.FileSystemLoader(searchpath='./template/')
template_env = jinja2.Environment(loader=template_loader)
template = template_env.get_template('netplan_template.yaml')


def get_user_input(prompt, default=None):
    result = input(prompt).strip()
    if not result:  # 检查用户是否直接按了 Enter 键
        return default
    return result


def get_default_network_info():
    eth = subprocess.check_output(
        "ip link show | grep 'BROADCAST,MULTICAST,UP' | grep -v 'lo' | awk '{print $2}' | sed 's/:$//'",
        shell=True
    ).decode().strip()
    ipv4 = subprocess.check_output(
        "ip addr show | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d/ -f1",
        shell=True
    ).decode().strip()
    gateway4 = subprocess.check_output(
        "ip route show | grep default | grep -Po 'via \\K\\S+'",
        shell=True
    ).decode().strip()
    return eth, ipv4, gateway4


def configure_static_ip():
    choice = input("是否要配置静态IP？(Y/N): ").strip().lower()
    if choice not in ['y', 'yes', '']:  # 检查用户输入
        print("您选择了不配置静态IP")
        return
    print("网络配置默认获取原则:\n"
          "网卡接口名称: ip link show | grep 'BROADCAST,MULTICAST,UP' | grep -v 'lo' | awk '{print $2}' | sed 's/:$//'\n"
          "ipv4地址：ip addr show | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d/ -f1\n"
          "网关地址：ip route show | grep default | grep -Po 'via \K\S+'\n"
          "1、如果输入了网卡接口名称，请确保网卡可用，建议回车键默认 \n"
          "2、ipv4地址，默认为，当前ip地址+输入的第4位，建议从101开始，避免ip冲突\n"
          "3、网关地址,默认为当前网关地址，不建议设置")
    eth_current, ipv4_current, gateway4_current = get_default_network_info()
    eth = get_user_input(f"网卡接口名称(默认: {eth_current}): ", eth_current)
    gateway4 = get_user_input(f"网关地址(默认: {gateway4_current}): ", gateway4_current)
    ipv4_default = f"{ipv4_current.split('.')[0]}.{ipv4_current.split('.')[1]}.{ipv4_current.split('.')[2]}.{101}"
    ipv4 = get_user_input(f"当前IPv4地址(({ipv4_current.split('.')[0]}.{ipv4_current.split('.')[1]}.{ipv4_current.split('.')[2]}.2~254),当前: {ipv4_current}): ", ipv4_default)
    nameservers_input = get_user_input("DNS地址(默认阿里云223.5.5.5,223.6.6.6): ", '223.5.5.5,223.6.6.6')
    nameservers = [ns.strip() for ns in nameservers_input.split(',')]

    # 根据用户输入构建配置字符串
    config_str = template.render(
        eth=eth,
        addresses=ipv4 + "/24",
        gateway4=gateway4,
        nameservers=nameservers
    )

    # 将配置写入新的Netplan配置文件
    netplan_file = "/etc/netplan/99-static-ip.yaml"
    with open(netplan_file, 'w') as file:
        file.write(config_str)

    # 设置文件权限为600
    os.chmod(netplan_file, 0o600)
    # 应用配置
    print("网络配置如下:\n" + config_str)
    print("ipv4地址为:" + ipv4 + " 系统即将重启")
    result = subprocess.run(["netplan", "apply"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode == 0:
        subprocess.run(["reboot"], check=True)
    else:
        print("应用网络配置时出错:\n" + result.stderr.decode())


if __name__ == "__main__":
    configure_static_ip()
